﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Unis.Framework.Core.Utility;
using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using KingRoad.EPM.PersonnelLogEntity.Model;

namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmDailySupervisionController : BaseController
    {
        /// <summary>
        /// 监理单位日报列表
        /// </summary>
        /// <returns></returns>
        public ActionResult DailySupervisionList()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;

            var allSegmentCode = "";
            Get_JL_JC_ZDJL_SegmentInfo.ForEach(t =>
            {
                allSegmentCode += "'" + t.SEGMENT_CODE + "',";
            });

            allSegmentCode = allSegmentCode.TrimEnd(',');

            //TODO：MOKANSA-权限变更
            var list1 = PlmDailysupervisionUIRule.GetInfoListByCondition(allSegmentCode, "");


            var groupWorkDate = list1.GroupBy(t => t.Ds_WorkDate).ToList();

            var retList = new List<PlmDailysupervisionInfo>();
            groupWorkDate.ForEach(t =>
            {
                //每条数据按照时期分组后，只取第一条记录
                retList.Add(t.ToList().FirstOrDefault());
            });




            var splitList = PlmDailysupervisionUIRule.GetEntityListByContionRe<PlmDailysupervisionInfo>(ViewBag.pageNum,
                ViewBag.numPerPage, "Ds_WorkDate", retList);
            return View(new PlmDailysupervisionViewModel { ThePlmDailysupervisionList = splitList });
        }
        /// <summary>
        /// 监理单位日报添加
        /// </summary>
        /// <returns></returns>
        public ActionResult DailySupervisionAdd(string target, string id)
        {

            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.工程_监理日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.工程_监理日志;
            ViewBag.OperationType = target;
            if (target == "add")
            {
                //附件
                var assisId = GenerateRandom();
                var assisIdRet = 0;
                CreateAssistId(PlmDailysupervisionUIRule, assisId, out assisIdRet);
                ViewBag.AssisId = assisIdRet;

                ViewBag.LoginUserId = GetLoginUserId;
                ViewBag.LoginUserName = GetLoginUserName;

                if (GetLoginUserOrganizeEntity.Code == null)
                {
                    return Content("<script>alert('当前用户没有添加权限,请使用拥有权限的人员登录后添加!')</script>");
                }


                switch (GetLoginUserOrganizeEntity.Code)
                {
                    case "JC":
                        ViewBag.Ds_DirectorSection = GetJCProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        ViewBag.Ds_SupervisorName = GetJCProjectSegmentInfo.FirstOrDefault().SEGMENT_DEPARTNAME;
                        break;
                    case "ZDJL":
                        ViewBag.Ds_DirectorSection = GetZDJLProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        ViewBag.Ds_SupervisorName = GetZDJLProjectSegmentInfo.FirstOrDefault().SEGMENT_DEPARTNAME;
                        break;
                    case "JL":
                        ViewBag.Ds_DirectorSection = GetJLProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        ViewBag.Ds_SupervisorName = GetJLProjectSegmentInfo.FirstOrDefault().SEGMENT_DEPARTNAME;
                        break;
                }
                return View();
            }
            else
            {
                if (GetLoginUserOrganizeEntity.Code == null)
                {
                    return Content("<script>alert('当前用户没有修改权限,请使用拥有权限的人员登录后修改!')</script>");
                }

                var vm = new PlmDailysupervisionViewModel();
                var dsDirectorSection = "";
                var dsSupervisorName = "";
                switch (GetLoginUserOrganizeEntity.Code)
                {
                    case "JC":
                        dsDirectorSection = GetJCProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        dsSupervisorName = GetJCProjectSegmentInfo.FirstOrDefault().SEGMENT_DEPARTNAME;
                        break;
                    case "ZDJL":
                        dsDirectorSection = GetZDJLProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        dsSupervisorName = GetZDJLProjectSegmentInfo.FirstOrDefault().SEGMENT_DEPARTNAME;
                        break;
                    case "JL":
                        dsDirectorSection = GetJLProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        dsSupervisorName = GetJLProjectSegmentInfo.FirstOrDefault().SEGMENT_DEPARTNAME;
                        break;
                }

                ViewBag.Ds_DirectorSection = dsDirectorSection;
                ViewBag.Ds_SupervisorName = dsSupervisorName;
                ViewBag.LoginUserId = GetLoginUserId;
                ViewBag.LoginUserName = GetLoginUserName;


                //var obj = PlmDailysupervisionUIRule.GetObjetById(id);

                //TODO:根据登陆人，替换”YLZD-2“内容
                var directorSecSqlStr = String.Format("'{0}'", dsDirectorSection);
                var entity = PlmDailysupervisionUIRule.GetInfoListByCondition(directorSecSqlStr, id).FirstOrDefault();
                vm.ThePlmDailysupervision = entity;
                //附件
                var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(entity.Assist_ID, "DailySupervision_Rules");//  BizType类型
                ViewBag.AssisId = entity.Assist_ID;
                ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
                ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

                return View(vm);
            }
        }

        public ActionResult DailySupervisionAddHandle(PlmDailysupervisionViewModel vm)
        {
            if (vm == null)
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "操作失败",
                    }
                };
            }
            dynamic jsonReturn = new ExpandoObject();
            string operation_str = string.Empty;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                if (vm.OperationType == "add")
                {
                    operation_str = "添加";
                    vm.ThePlmDailysupervision.Ds_ID = Guid.NewGuid().ToString();
                    //TODO:根据权限，暂时固定
                    vm.ThePlmDailysupervision.Ds_ContractNumber = vm.ThePlmDailysupervision.Ds_DirectorSection;

                    //TODO:根据权限，需要获取一些信息
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmDailysupervision.Assist_ID = AssistID;
                    var ret = PlmDailysupervisionUIRule.InsertPlmDailysupervision(vm.ThePlmDailysupervision);
                }
                if (vm.OperationType == "edit")
                {
                    operation_str = "更新";
                    var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                    vm.ThePlmDailysupervision.Assist_ID = AssistID;
                    var ret = PlmDailysupervisionUIRule.UpdatePlmDailysupervision(vm.ThePlmDailysupervision);
                }
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = string.Format("{0}成功", operation_str), navTabId = "PersonnelLog.PlmDailySupervision.DailySupervisionList", rel = "", callbackType = "closeCurrent", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = string.Format("{0}失败", operation_str) };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };

        }


        public ActionResult DailySupervisionDelete(string workDate)
        {
            if (GetLoginUserOrganizeEntity.Code == null)
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "当前用户没有删除权限,请使用拥有权限的人员登录后删除!",
                    }
                };
            }
            if (String.IsNullOrEmpty(workDate))
            {
                return new JsonResult()
                {
                    Data = new
                    {
                        statusCode = "300",
                        message = "删除失败",
                    }
                };
            }


            dynamic jsonReturn = new ExpandoObject();
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                var vm = new PlmDailysupervisionViewModel();
                var dsDirectorSection = "";

                switch (GetLoginUserOrganizeEntity.Code)
                {
                    case "JC":
                        dsDirectorSection = GetJCProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        break;
                    case "ZDJL":
                        dsDirectorSection = GetZDJLProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        break;
                    case "JL":
                        dsDirectorSection = GetJLProjectSegmentInfo.FirstOrDefault().SEGMENT_CODE;
                        break;
                }

                //var obj = PlmDailysupervisionUIRule.GetObjetById(id);

                //TODO:根据登陆人，替换”YLZD-2“内容
                var directorSecSqlStr = String.Format("'{0}'", dsDirectorSection);
                var entity = PlmDailysupervisionUIRule.GetInfoListByCondition(directorSecSqlStr, workDate).FirstOrDefault();
                PlmDailysupervisionUIRule.DeleteObjetById(entity.Ds_ID);
            });
            if (isScuess)
            {
                jsonReturn = new { statusCode = "200", message = "删除成功", navTabId = "PersonnelLog.PlmDailySupervision.DailySupervisionList", rel = "", callbackType = "", forwardUrl = "", confirmMsg = "" };
            }
            else
            {
                jsonReturn = new { statusCode = "300", message = "删除失败" };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };

        }


        /// <summary>
        /// 监理单位日报查看
        /// </summary>
        /// <returns></returns>
        public ActionResult DailySupervisionDetail(string workDate)
        {
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.工程_监理日志);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.工程_监理日志;
            //TODO：需要根据权限来确认当前登陆人的信息
            var vm = new PlmDailysupervisionViewModel();


            var allSegmentCode = "";
            Get_JL_JC_ZDJL_SegmentInfo.ForEach(t =>
            {
                allSegmentCode += "'" + t.SEGMENT_CODE + "',";
            });

            allSegmentCode = allSegmentCode.TrimEnd(',');

            //var directorSecSqlStr = String.Format("'{0}'", directorSection);
            var retList = PlmDailysupervisionUIRule.GetInfoListByCondition(allSegmentCode, workDate);
            //if(retList)

            //TODO:先暂时固定，后续需要动态显示
            var sectionName = "";

            retList.ForEach(t =>
            {
                if (t.Ds_DirectorSection.Contains("ZJ-1") && !sectionName.Contains("1第一总监办"))
                {
                    sectionName += "1第一总监办、";
                }
                else if (t.Ds_DirectorSection.Contains("ZJ-2") && !sectionName.Contains("1第二总监办"))
                {
                    sectionName += "1第二总监办、";
                }
                else if (t.Ds_DirectorSection.Contains("JC") && !sectionName.Contains("3检测单位"))
                {
                    sectionName += "3检测单位、";
                }
                else if (t.Ds_DirectorSection.Contains("ZD") && !sectionName.Contains("2驻地单位"))
                {
                    sectionName += "2驻地单位、";
                }
            });
            var tempSectionName = "";
            sectionName = sectionName.TrimEnd('、');
            sectionName.Split('、').ToList().OrderBy(t => t).ToList().ForEach(t =>
            {
                tempSectionName += t.Substring(1) + "、";
            });

            tempSectionName = tempSectionName.TrimEnd('、');

            tempSectionName += "工作进度日报表";

            KingRoad.EPM.ProjectInfoEntity.PROJECT_SEGMENT currentLoginSegment = null;
            switch (GetLoginUserOrganizeEntity.Code)
            {
                case "JC":
                    currentLoginSegment = GetJCProjectSegmentInfo.FirstOrDefault();

                    break;
                case "ZDJL":
                    currentLoginSegment = GetZDJLProjectSegmentInfo.FirstOrDefault();

                    break;
                case "JL":
                    currentLoginSegment = GetJLProjectSegmentInfo.FirstOrDefault();

                    break;
            }
            if (GetLoginUserOrganizeEntity.Code == null)
            {
                currentLoginSegment = GetJLProjectSegmentInfo.FirstOrDefault();
            }

            //TODO：先暂时固定，后续根据登陆人信息显示
            vm.ReportContractNum = currentLoginSegment.SEGMENT_CODE;
            vm.ReportUnitName = currentLoginSegment.SEGMENT_DEPARTNAME;
            vm.ReportDate = workDate;
            vm.ReportTitle = tempSectionName;


            //组合报表格式
            vm.GetType().GetProperties().Where(t => t.Name.StartsWith("Report_")).ToList().ForEach(t =>
            {
                var proptertyName = t.Name.Substring(t.Name.IndexOf("_", StringComparison.Ordinal) + 1);
                var value = "";
                retList.ForEach(r =>
                {
                    if (proptertyName == "Ds_Remark")
                    {
                        var biaoDuanHao= Reflection.GetProperty(r, "Ds_DirectorSection").ToString();



                        value += Reflection.GetProperty(r, proptertyName) == null ? "$"
                            : "<span style='font-weight: 600;'>(" + biaoDuanHao+")备注：</span><br/>"+ Reflection.GetProperty(r, proptertyName).ToString() + "$";
                    }
                    else
                        value += Reflection.GetProperty(r, proptertyName) == null ? "$"
                            : Reflection.GetProperty(r, proptertyName).ToString() + "$";
                });
                if (!String.IsNullOrEmpty(value))
                    value = value.Substring(0, value.Length - 1);
                Reflection.SetProperty(vm, t.Name, value);
            });
            return View(vm);
        }




        public ActionResult SplitPage(PlmDailysupervisionViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条

            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);

            ViewBag.type = Request.Form["type"];
            ViewBag.time = Request.Form["time"];

            string sql = " 1=1 ";
            if (ViewBag.type != "")
                sql += " and Ds_DirectorSection='" + ViewBag.type + "' ";
            if (ViewBag.time != "")
                sql += " and Ds_WorkDate='" + ViewBag.time + "' ";


            var list = PlmDailysupervisionUIRule.GetDailysupervisionForPage(ViewBag.pageNum, ViewBag.numPerPage, "Ds_WorkDate", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("DailySupervisionList", new PlmDailysupervisionViewModel { ThePlmDailysupervisionList = list });
        }

    }
}
